package com.ctgu.demo.controller;

import com.ctgu.demo.utils.ApiResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/opsForHash")
public class OpsForHashController {

    private final RedisTemplate<String, Object> redisTemplate;

    public OpsForHashController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String USER_KEY = "ctgu:user:1001";
    private static final String ARTICLE_STATS_KEY = "ctgu:article:stats";
    private static final String ARTICLE_HASH_KEY_1 = "ctgu:articleId:1";
    private static final String ARTICLE_HASH_KEY_2 = "ctgu:articleId:2";

    // http://localhost:8080/opsForHash/userInfo
    // 用户信息管理：用户的信息如姓名、邮箱、积分可以存储到 Redis 中，快速地读取和更新。
    @GetMapping("userInfo")
    public ApiResult userInfo() {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "Alex");
        userMap.put("email", "alex@example.com");
        userMap.put("points", 150);
        redisTemplate.opsForHash().putAll(USER_KEY, userMap);

        // 增加积分
        redisTemplate.opsForHash().increment(USER_KEY, "points", 50);

        // 获取所有字段和值
        Map<Object, Object> userInfo = redisTemplate.opsForHash().entries(USER_KEY);
        return ApiResult.success("存储用户信息成功", userInfo);
    }

    // http://localhost:8080/opsForHash/article
    // 博客文章统计：每篇文章需要记录阅读量和点赞量，可以使用 Hash 存储这些统计数据。
    @GetMapping("article")
    public ApiResult articleStats() throws JsonProcessingException {
        // 初始化文章统计数据
        redisTemplate.opsForHash().putIfAbsent(ARTICLE_STATS_KEY, ARTICLE_HASH_KEY_1, "{\"views\":1000, \"likes\":500}");
        redisTemplate.opsForHash().putIfAbsent(ARTICLE_STATS_KEY, ARTICLE_HASH_KEY_2, "{\"views\":800, \"likes\":300}");

        String statsJson = (String) redisTemplate.opsForHash().get(ARTICLE_STATS_KEY, ARTICLE_HASH_KEY_1);

        // 明确指定泛型类型
        Map<String, Object> articleStats = objectMapper.readValue(statsJson, new TypeReference<Map<String, Object>>() {
        });

        // 安全更新阅读量
        int views = Integer.parseInt(String.valueOf(articleStats.get("views")));
        articleStats.put("views", views + 1);

        // 保存回 Redis
        redisTemplate.opsForHash().put(ARTICLE_STATS_KEY, ARTICLE_HASH_KEY_1, objectMapper.writeValueAsString(articleStats));
        return ApiResult.success("获取阅读量、点赞量成功", articleStats);
    }
}
